package com.example.servlet;


import com.example.Service.NewsService;
import com.example.Service.UserService;
import com.example.pojo.News;
import com.example.pojo.User;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet(name = "AddNewsServlet", value = "/AddNewsServlet")
public class AddNewsServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(req.getReader());
        StringBuffer sbuffer =new  StringBuffer();
        String s="";
        while ((s=br.readLine())!=null){
            sbuffer.append(s);
        }
        System.out.println(sbuffer.toString());
        Gson gson =new Gson();
        News news =gson.fromJson(sbuffer.toString(), News.class);
        Map<String,Object> map=new HashMap<>();
        NewsService newsService=new NewsService();
    int flag = newsService.addNews(news);
        if (flag>0){
            map.put("code",200);
            map.put("msg","添加成功");
        }else {
            map.put("code",500);
            map.put("msg","添加失败");
        }
        String json =gson.toJson(map);
        resp.getWriter().append(json);
    }

    public void destroy() {
    }
}
